package com.eshop.web.controllers.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSONObject;
import com.eshop.common.constant.CoreConstant;
import com.eshop.common.util.security.MD5;
import com.eshop.frameworks.core.controller.BaseController;
import com.eshop.model.mongodb.EUser;
import com.eshop.service.mongodb.EUserService;

@Controller
public class LoginController extends BaseController {

	private static final Logger logger = Logger
			.getLogger(LoginController.class);

	@Autowired
	private EUserService euserService;

	@RequestMapping(value = "/regist", method = RequestMethod.GET)
	public ModelAndView regist(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("regist.httl");
		EUser user = (EUser) this.getSessionAttribute(request,
				CoreConstant.USER_SESSION_NAME);
		if (user != null) {
			mav.setViewName("redirect:/index");
			return mav;
		}
		setVar(mav);
		return mav;
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView login(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("login.httl");
		EUser user = (EUser) this.getSessionAttribute(request,
				CoreConstant.USER_SESSION_NAME);
		if (user != null) {
			mav.setViewName("redirect:/index");
			return mav;
		}
		setVar(mav);
		return mav;
	}

	@RequestMapping("/agreement")
	public ModelAndView agreement(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("agreement.httl");
		setVar(mav);
		return mav;
	}

	@RequestMapping(value = "/regist", method = RequestMethod.POST)
	public ModelAndView regist(EUser euser,
			@RequestParam(required = false) String keyMobile,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView modelAndView = new ModelAndView("redirect:/index");
		try {
			String mobile = euser.getMobile();
			if (mobile != null && keyMobile != null
					&& keyMobile.equals(MD5.getMD5(mobile))) {
				String cd = (String) this.getSessionAttribute(request,
						euser.getMobile() + "_code");
				if (cd != null && euser.getCaptcha() != null
						&& euser.getCaptcha().equals(cd)) {
					euser.setPassword(MD5.getMD5(euser.getPassword()));
					euser.setRegTime(new Date());
					euser.setIsMobileVerified(1);
					euser.setSource("phone");
					euser.setUsername(mobile);
					euserService.save(euser);
					euser = euserService.getByMobile(euser);
					this.setSessionAttribute(request, response,
							CoreConstant.USER_SESSION_NAME, euser);
					setCookieUserId(response, euser.getId());
				} else {
					modelAndView.addObject("user", euser);
					modelAndView.setViewName("regist.httl");
					modelAndView.addObject("captcha_error", true);
					setVar(modelAndView);
				}
			} else {
				modelAndView.addObject("user", euser);
				modelAndView.setViewName("regist.httl");
				modelAndView.addObject("captcha_error", true);
				setVar(modelAndView);
			}
		} catch (Exception e) {
			logger.error("LoginController.regist", e);
		}
		return modelAndView;
	}

	@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
	public ModelAndView doLogin(EUser euser, HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("redirect:/index");
		String succURL = request.getParameter("succURL");
		mav.addObject("succURL", succURL);
		String captcha = (String) this.getSessionAttribute(request,
				CoreConstant.RAND_CODE);
		if (euser.getCaptcha().equals(captcha)) {
			EUser user = euserService.getByMobileAndPwd(euser);
			if (user != null) {
				this.setSessionAttribute(request, response,
						CoreConstant.USER_SESSION_NAME, user);
				setCookieUserId(response, euser.getId());
				if (StringUtils.isNotBlank(succURL)) {
					request.setAttribute("succURL", succURL);
					mav.setViewName("login_success.httl");
				} else if (user.getIsShopper() != null
						&& user.getIsShopper() == 1) {
					mav.setViewName("redirect:/ucenter");
				}
			} else {
				mav.addObject("user", euser);
				mav.setViewName("login.httl");
				mav.addObject("name_error", true);
				setVar(mav);
			}
		} else {
			mav.addObject("user", euser);
			mav.setViewName("login.httl");
			mav.addObject("captcha_error", true);
			setVar(mav);
		}
		return mav;
	}

	/**
	 * 用于跨域登录
	 * 
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/jsonpUserLogin")
	@ResponseBody
	public String jsonpUserLogin(@ModelAttribute("user") EUser euser,
			@RequestParam String suleback, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", true);
		map.put("message", "登录成功");
		logger.debug("开始jsnopUserLogin登录，");
		try {
			EUser user = euserService.getByMobileAndPwd(euser);
			if (user != null) {
				this.setSessionAttribute(request, response,
						CoreConstant.USER_SESSION_NAME, user);
				setCookieUserId(response, euser.getId());
			} else {
				map.put("success", false);
				map.put("message", "请输入正确的用户名密码");
			}
		} catch (Exception e) {
			map.put("success", false);
			map.put("message", "请输入正确的用户名密码");
		}
		return suleback + "(" + JSONObject.toJSONString(map) + ")";
	}

	@RequestMapping("/isLogin")
	@ResponseBody
	public String isLogin(@RequestParam String suleback,
			HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		EUser user = (EUser) this.getSessionAttribute(request,
				CoreConstant.USER_SESSION_NAME);
		map.put("isLogin", user != null);
		return suleback + "(" + JSONObject.toJSONString(map) + ")";
	}

	@RequestMapping("/logout")
	public RedirectView logout(HttpServletRequest request,
			HttpServletResponse response) {
		this.clear(request, response);
		RedirectView r = new RedirectView("/index");
		return r;
	}

}
